module Fluxr::Helpers
  def fluxr_response_xml(&block)
    instruct!
    tag!("response", "xmlns:fluxr" => "http://nowhere.com") do
      yield
    end
  end
  
  def workflow_status_xml(status)
    tag!("process-status", :wfid => status.wfid) do
      tag!("errors") do
        status.errors.each do |fei, e|
          process_error_xml(e)
        end
      end
      tag!("expressions") do
        status.expressions.each do |exp|
          tag!("expression", :fei => exp.fei) {exp.to_s}
        end
      end
    end
  end
  
  def workitem_xml(wi)
    tag!("workitem", :fei => wi.fei, :participant_name => wi.participant_name) do
      wi.attributes.delete_if{|k,v| k =~ /^_/}.each do |k,v|
        tag!(k) {v}
      end
    end
  end
  
  def participant_xml(p)
    #if p[0].kind_of? Regexp
      tag!("participant") do
        # FIXME: this should probably be CDATA
        tag!("name-pattern") {p[0]}
        tag!("class") {p[1].class}
      end
    #else
    #  p.each do |p2| 
    #    tag!("participant") {participant(p2)}
    #  end
    #end
  end
  
  def process_error_xml(e)
    tag!("process-error", :date => e.date, :fei => e.fei) do
      tag!("message") {e.message}
      tag!("stacktrace") {e.stacktrace}
      workitem_xml(e.workitem)
    end
  end
end